package dbrpc

import (
	"bytes"
	"database/sql"
	"dub/define/grpcmodel"
	"dub/utils"
	"golang.org/x/net/context"
)

//与角色有关的数据库操作
type DbRpcRole struct {
	log *utils.Logger
}

func (r *DbRpcRole) FindRole(ctx context.Context, args *grpcmodel.ModelDbRpcRoleReqFind) (reply *grpcmodel.ModelDbRpcRoleResFindRole, err error) {
	reply = &grpcmodel.ModelDbRpcRoleResFindRole{}
	params := make([]interface{}, 0)
	sql_str := bytes.Buffer{}
	sql_str.WriteString("select r.roleId,r.roleName,UNIX_TIMESTAMP(ur.urAddTime),UNIX_TIMESTAMP(ur.urEditTime),ur.urMain from dubrole r LEFT JOIN dubuserole ur on r.roleId=ur.roleId where r.roleStatus=1")
	if !args.GetIsJustRole() {
		sql_str.WriteString(" and ur.useRoleStatus=1 and ur.urMain=1")
	}
	if args.GetUserId() > 0 {
		sql_str.WriteString(" and ur.userId=?")
		params = append(params, args.GetUserId())
	}
	if args.GetRoleCode() != "" {
		sql_str.WriteString(" and r.roleCode=?")
		params = append(params, args.GetRoleCode())
	}
	if args.GetRoleId() > 0 {
		sql_str.WriteString(" and r.roleId=?")
		params = append(params, args.GetRoleId())
	}

	sql_str.WriteString(" limit 1")
	sql_buf := sql_str.String()
	r.log.Infof("def_func_db_role.go FindRole method exec %s params is %+v\n", sql_buf, params)
	dbAccounts := NewDbProxy().Get(DB_Accounts)
	row := dbAccounts.QueryRow(sql_buf, params...)
	for {
		var (
			roleId, urMain, urAddTime_str, urEditTime_str sql.NullInt64
			roleName                                      sql.NullString
		)
		err = row.Scan(&roleId, &roleName, &urAddTime_str, &urEditTime_str, &urMain)
		switch {
		case err == sql.ErrNoRows:
			err = nil
			reply.Err = 1
		case err != nil:
			reply.Err = 2
			r.log.Errorf("def_fun_db_role.go FindRole method row.Scan err. %v\n", err)
		default:
			model := &grpcmodel.ModelDbRpcRole{}
			if roleId.Valid {
				model.RoleId = uint32(roleId.Int64)
			}
			if roleName.Valid {
				model.RoleName = roleName.String
			}
			if urMain.Valid && urMain.Int64 == 1 {
				model.UrMain = true
			}

			if urAddTime_str.Valid {
				model.UrAddTime = uint64(urAddTime_str.Int64)
			}

			if urEditTime_str.Valid {
				model.UrEditTime = uint64(urEditTime_str.Int64)
			}
			reply.ModelDbRpcRole = model
		}
		break
	}
	return
}

//根据查询条件相应的行政区
func (r *DbRpcRole) Find(ctx context.Context, args *grpcmodel.ModelDbRpcRoleReqFind) (reply *grpcmodel.ModelDbRpcRoleResFind, err error) {
	reply = &grpcmodel.ModelDbRpcRoleResFind{}
	return
}

var d_dbRpcRole *DbRpcRole

func NewDbRpcRole() *DbRpcRole {
	if d_dbRpcRole == nil {
		d_dbRpcRole = &DbRpcRole{
			log: utils.NewLogger(),
		}
	}
	return d_dbRpcRole
}
